import { MessageRouter } from "@utils/messaging";
import { MessageType, type CountElementsRequest, type InjectCSSRequest } from "@utils/types";
import { SELECTORS } from "@utils/constants";

export function setupMessageHandlers(components: { extensionPanel: { toggle: () => void } }) {
  const messageRouter = new MessageRouter();

  messageRouter.register(MessageType.HIGHLIGHT_LINKS, async () => {
    const links = document.querySelectorAll(SELECTORS.LINKS);
    const isHighlighted = links[0]?.classList.contains("wxt-highlighted");
    links.forEach((link) => {
      const element = link as HTMLElement;
      if (isHighlighted) {
        element.classList.remove("wxt-highlighted");
        element.style.backgroundColor = "";
        element.style.border = "";
        element.style.borderRadius = "";
      } else {
        element.classList.add("wxt-highlighted");
        element.style.backgroundColor = "#ffeb3b";
        element.style.border = "2px solid #ff5722";
        element.style.borderRadius = "4px";
        element.style.transition = "all 0.3s ease";
      }
    });
    if (!isHighlighted) {
      setTimeout(() => {
        links.forEach((link) => {
          const element = link as HTMLElement;
          element.classList.remove("wxt-highlighted");
          element.style.backgroundColor = "";
          element.style.border = "";
          element.style.borderRadius = "";
        });
      }, 5000);
    }
    return { success: true, timestamp: Date.now() } as any;
  });

  messageRouter.register(MessageType.COUNT_ELEMENTS, async (message: CountElementsRequest) => {
    const count = document.querySelectorAll(message.selector).length;
    return { success: true, count, selector: message.selector, timestamp: Date.now() } as any;
  });

  messageRouter.register(MessageType.SCROLL_TO_TOP, async () => {
    window.scrollTo({ top: 0, behavior: "smooth" });
    return { success: true, timestamp: Date.now() } as any;
  });

  messageRouter.register(MessageType.TOGGLE_EXTENSION_UI, async () => {
    components.extensionPanel.toggle();
    return { success: true, timestamp: Date.now() } as any;
  });

  messageRouter.register(MessageType.INJECT_CSS, async (message: InjectCSSRequest) => {
    const styleId = message.id || "wxt-injected-style";
    const existingStyle = document.getElementById(styleId);
    if (existingStyle) existingStyle.remove();
    const style = document.createElement("style");
    style.id = styleId;
    style.textContent = message.css;
    document.head.appendChild(style);
    return { success: true, timestamp: Date.now() } as any;
  });

  // STORAGE_CHANGED 由 @content/state/appState.ts 专责处理，避免重复响应

  messageRouter.startListening();
}
